package com.training.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.training.dao.EmployeeDAO;
import com.training.dto.EmployeeDTO;
import com.training.entities.Employee;

@Service("employeeService")
public class EmployeeService {

	@Autowired
	EmployeeDAO employeeDAO;

	public EmployeeDAO getEmployeeDAO() {
		return employeeDAO;
	}

	public void setEmployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}

	public EmployeeDTO validateEmployee(String userName, String password) {
		Employee employee = employeeDAO.validateEmployee(userName, password);
		EmployeeDTO employeeDTO = null;

		if (employee != null) {
			employeeDTO = new EmployeeDTO();

			employeeDTO.setFirstName(employee.getEmployeeFirstName());
			employeeDTO.setLastName(employee.getEmployeeLastName());
			employeeDTO.setUserName(employee.getUserName());
			employeeDTO.setPassword(employee.getPassword());
		}
		return employeeDTO;
	}

	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public boolean saveNewEmployee(EmployeeDTO employeeDTO) {

		boolean isCreated = false;
		
		try {
			
			Employee employee = new Employee();

			employee.setEmployeeId(employeeDTO.getEmployeeId());
			employee.setEmployeeFirstName(employeeDTO.getFirstName());
			employee.setEmployeeLastName(employeeDTO.getLastName());
			employee.setUserName(employeeDTO.getUserName());

			employeeDAO.saveNewEmployee(employee);
			isCreated = true;

		} catch (Exception e) {
			// TODO: handle exception
		}
				
		return isCreated;

	}
}
